package com.kltn.zigo;

import java.util.ArrayList;
import java.util.HashMap;

import com.kltn.zigo.NewPostActivity.LoadProvince;
import com.kltn.zigo.data.adapter.PlaceAdapter;
import com.kltn.zigo.data.adapter.ProvinceAdapter;
import com.kltn.zigo.data.loader.PlaceLoader;
import com.kltn.zigo.data.loader.ProvinceLoader;
import com.kltn.zigo.process.JSONParser;
import com.kltn.zigo.zingme.sdk.ZingMeSDK;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("NewApi")
public class ListPlaceActivity extends Activity implements OnClickListener {
	
	JSONParser jParser = new JSONParser();
    String provinceID = "1";

	// Progress Dialog
	private ProgressDialog pDialog;

    private ArrayList<HashMap<String, String>> data;
    ArrayList<HashMap<String, String>> provincesList;
	ProvinceAdapter provinceAdapter;
	ListView listProvince;
    
	ListView list;
	TextView tvProvince;
	EditText inputSearch;
	PlaceAdapter adapter;	
    private static LayoutInflater inflater=null;
    String placeIdClicked = "";
    
    String userid;
	String username;
	String userdisplayname;
	String useravatarurl;
	
    private MenuItem btnMenu;
    private MenuItem btnSearch;
    private MenuItem btnProfile;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_place);		
		
		ActionBar actionBar = getActionBar();		
		actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#b51d21")));		    
        
		userid = getIntent().getStringExtra("userid");
		username = getIntent().getStringExtra("username");
		userdisplayname = getIntent().getStringExtra("userdisplayname");
		useravatarurl = getIntent().getStringExtra("useravatarurl");
		
		list=(ListView)findViewById(R.id.list_places);
		tvProvince = (TextView)findViewById(R.id.tvProvince);
        tvProvince.setText("TP. Hồ Chí Minh");			
		tvProvince.setOnClickListener(this);
		
        new LoadPlaceAsync().execute();
        
        
        list.setOnItemClickListener(new OnItemClickListener() {
        	@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {							
        		View vi=view;
		        if(view==null)
		            vi = inflater.inflate(R.layout.item_list_place, null);

		        TextView placeID = (TextView)vi.findViewById(R.id.tvID);
		        
		        placeIdClicked = placeID.getText().toString();
		        
		        Intent i=new Intent(ListPlaceActivity.this,PlaceDetailActivity.class);
		        i.putExtra("placeid", placeIdClicked);
		        i.putExtra("userid",userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	//public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.list_place, menu);

		btnMenu = menu.findItem(R.id.btn_menu);
		btnSearch = menu.findItem(R.id.btn_search);
		btnProfile = menu.findItem(R.id.btn_profile);
		
		return true;
	}
	
	 @Override
	  public boolean onOptionsItemSelected(MenuItem item) {
		 switch (item.getItemId()) {
		   
		    case R.id.btn_profile:
		    {
		    	Intent i=new Intent(ListPlaceActivity.this,ProfileUserActivity.class);
		        i.putExtra("userid", userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
		        
		        i.putExtra("useridView","");
		        i.putExtra("usernameView", "");
		        i.putExtra("userdisplaynameView","");
		        i.putExtra("useravatarurlView", "");
			    startActivity(i);
		    	break;
		    }
		    	
		    case R.id.btn_search:
		    {
		    	Intent i=new Intent(getApplicationContext(),ListPlaceActivity.class);
		    	i.putExtra("userid",userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
			    break;
		    }
		    
		    case R.id.btn_menu:
		    {
		    	Intent i=new Intent(ListPlaceActivity.this,MainActivity.class);
		        i.putExtra("userid", userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
		    	break;
		    }
		 }
		 return super.onOptionsItemSelected(item);
	  }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tvProvince:
		{
			//final Dialog dialog = new Dialog(NewPostActivity.this);
			final Dialog dialog = new Dialog(ListPlaceActivity.this);
			dialog.setContentView(R.layout.dialog_province_district);
			dialog.setTitle("Tỉnh - Thành phố");
			dialog.setCanceledOnTouchOutside(true);
            listProvince = (ListView)dialog.findViewById(R.id.list_province_district);
            new LoadProvince().execute();
            
            listProvince.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View
		                view, int position, long id) {
					// TODO Auto-generated method stub
					View vi=view;
			        if(view==null)
			            vi = inflater.inflate(R.layout.item_list_address, null);

			        TextView prov_id = (TextView)vi.findViewById(R.id.tvID);
			        TextView prov_name = (TextView)vi.findViewById(R.id.tvProvinceDistrict);
			        
			        provinceID = prov_id.getText().toString();
			        tvProvince.setText(prov_name.getText().toString());		
			        new LoadPlaceAsync().execute();
			        dialog.dismiss();
				}
            	
			});
            
            dialog.show();
            
            break;
		}

		default:
			break;
		}
	}
	
        
    class LoadPlaceAsync extends AsyncTask<String, String, String>
    {
    	PlaceLoader placeload = new PlaceLoader(provinceID);
    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ListPlaceActivity.this);
			pDialog.setMessage("Loading places. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
    	
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
	    	//placeload = new PlaceLoader();
			
			data = placeload.GetPlace();
			return null;
		}
		
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					adapter = new PlaceAdapter(ListPlaceActivity.this, placeload, data);
					//adapter = new PlaceAdapter(ListPlaceActivity.this, placeload);
			        list.setAdapter(adapter);
			        
			        inputSearch = (EditText) findViewById(R.id.inputSearch);

                    inputSearch.addTextChangedListener(new TextWatcher() {

                        @Override
                        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                            // When user changed the Text
                            ListPlaceActivity.this.adapter.getFilter().filter(cs);   
                        }

                        @Override
                        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                int arg3) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void afterTextChanged(Editable arg0) {
                            // TODO Auto-generated method stub                          
                        }
                    });
				}
			});

		}
    }
    
	  //Load Province
	    class LoadProvince  extends AsyncTask<String, String, String>{	  
	    	
	    	ProvinceLoader provinceloader = new ProvinceLoader();
		    @Override
		    protected void onPreExecute() {
		    	super.onPreExecute();
	            pDialog = new ProgressDialog(ListPlaceActivity.this);
	            pDialog.setMessage("Loading province. Please wait...");
	            pDialog.setIndeterminate(false);
	            pDialog.setCancelable(false);
	            pDialog.show();	       
		    }

			@Override
			protected String doInBackground(String... args) {
				provincesList = provinceloader.GetProvince();
				return null;
		    }

		    //*//**
		    // * After completing background task Dismiss the progress dialog
		    // * **//*
		    protected void onPostExecute(String file_url) {
		    	pDialog.dismiss();
				// updating UI from Background Thread
				runOnUiThread(new Runnable() {
					public void run() {
						provinceAdapter = new ProvinceAdapter(ListPlaceActivity.this, provinceloader, provincesList);
						//adapter = new PlaceAdapter(ListPlaceActivity.this, placeload);
						listProvince.setAdapter(provinceAdapter);		        
				       
					}
				});
		    }
		}
		
}